package org.linlinjava.litemall.wx.web;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.service.LitemallAddressService;
import org.linlinjava.litemall.db.service.LitemallRegionService;
import org.linlinjava.litemall.wx.service.GetRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**

 * @author BestN 
 * @description 用户收货地址服务
 * @Date 2019/11/9 
 */
@RestController
@RequestMapping("/wx/address")
//@Validated
public class WxAddressController extends GetRegionService {
    private final Log logger = LogFactory.getLog(WxAddressController.class);

    @Autowired
    private LitemallAddressService addressService;
    @Autowired
    private LitemallRegionService regionService;

    /**
     *
     * @description 用户收货地址列表
     * @author BestN 
     * @date 2019/11/9 
     */
    @PostMapping("list")
    public Object list(HttpServletRequest request) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        Integer userId = Integer.parseInt(user.getUserid());
        List<LitemallAddress> addressList = addressService.queryByUid(userId);
        return ResponseUtil.okList(addressList);
    }

    /**
     * @description 收货地址详情
     * @author BestN 
     * @date 2019/11/9 
     */
    @PostMapping("detail")
    public Object detail(HttpServletRequest request, @NotNull Integer id) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        if (user == null) {
            return ResponseUtil.unlogin();
        }
        Integer userId = Integer.parseInt(user.getUserid());
        LitemallAddress address = addressService.query(userId, id);
        if (address == null) {
            return ResponseUtil.badArgumentValue();
        }
        return ResponseUtil.ok(address);
    }

    /**
     * @description 验证地址对象中的各个属性
     * @author BestN 
     * @date 2019/11/9 
     */
    private Object validate(LitemallAddress address) {
        String name = address.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        // 测试收货手机号码是否正确
        String mobile = address.getTel();

        //参数不对
        if (StringUtils.isEmpty(mobile)) {
            return ResponseUtil.fail(10001, "请填写手机号");
        }

        //验证手机号码格式
        if (!RegexUtil.isMobileExact(mobile)) {
            return ResponseUtil.fail(10001, "请填写正确的手机号");
        }

        List<Integer> codeList = address.getCodeList();
        if (codeList == null || codeList.size() < 1) {
            return ResponseUtil.fail(10001, "请选取省市县");
        }
        address.setProvince(null);
        address.setCity(null);
        address.setCounty(null);
        for (int i = 0; i < codeList.size(); i++) {
            Integer code = codeList.get(i);
            switch (i) {
                case 0:
                    //省
                    String province = regionService.findNameByCode(code);
                    address.setProvince(province);
                    break;
                case 1:
                    String city = regionService.findNameByCode(code);
                    address.setCity(city);
                    break;
                case 2:
                    String country = regionService.findNameByCode(code);
                    address.setCounty(country);
                    break;
                default:
                    break;
            }
        }

        //详细地址
        String detailedAddress = address.getAddressDetail();
        if (StringUtils.isEmpty(detailedAddress)) {
            return ResponseUtil.fail(10001, "请填写详细地址");
        }

        return null;
    }

    /**
     *  
     *
     * @description 添加或更新收货地址
     * @author BestN 
     * @date 2019/11/9 
     */
    @PostMapping("save")
    public Object save(HttpServletRequest request, @RequestBody LitemallAddress address) {
        XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        if (user == null) {
            return ResponseUtil.unlogin();
        }
        if (address.getIsDefault() == null) {
            return ResponseUtil.badArgument();
        }
        Integer userId = Integer.parseInt(user.getUserid());


        //如果该地址的默认选项为true，则重置其他收货地址的默认选项

        //如果该地址未设置为默认地址，但是是该用户的唯一地址，则自动设为默认地址
        List<LitemallAddress> list = addressService.queryByUid(userId);
        if (list == null || list.size() < 1) {
            address.setIsDefault(true);
        }

        Object error = validate(address);
        if (error != null) {
            return error;
        }

        //如果id为空，则是新增一条收货地址，如果有id,则为更新该id的现存信息
        if (address.getId() == null || address.getId().equals(0)) {

            if (address.getIsDefault()) {
                addressService.resetDefault(userId);
            }
            address.setId(null);
            address.setUserId(userId);
            addressService.add(address);
        } else {
            address.setUserId(userId);
            if (address.getIsDefault()) {
                addressService.resetDefault(userId);
            }
            if (addressService.update(address) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
        }
        return ResponseUtil.ok(detail(request, address.getId()));
    }

    /**
     *  
     *
     * @description 删除收货地址
     * @author BestN 
     * @date 2019/11/9 
     */
    @PostMapping("delete")
    public Object delete(@RequestBody String msg) {
        Integer id = JacksonUtil.parseInteger(msg, "id");
        if (id == null) {
            return ResponseUtil.badArgument();
        }
		LitemallAddress address =  addressService.findById(id);
        if (address == null) {
        	return ResponseUtil.badArgumentValue();
		}
        if (address.getIsDefault()) {
        	List<LitemallAddress> temp = addressService.queryByUid(address.getUserId());
        	if (temp.size() > 1) {
        		int i = 0;
        		while (temp.get(i).getIsDefault()) {
        			i ++;
				}
        		temp.get(i).setIsDefault(true);
        		addressService.update(temp.get(i));
			}
		}
		addressService.delete(id);
        return ResponseUtil.ok();
    }

    /**
     * 翻译汉字和相应区域代码
     *
     * @author Riko
     * @date 2019/12/18
     * @update 2019/12/18
     **/
    @PostMapping("translate")
    public Object translate(@RequestBody String msg) {
        String province = JacksonUtil.parseString(msg, "province");
        String city = JacksonUtil.parseString(msg, "city");
        String country = JacksonUtil.parseString(msg, "country");
        List<Integer> codeList;
        if (!org.apache.commons.lang3.StringUtils.isNoneEmpty()) {
            codeList = regionService.findCodeByName(province, city, country);
            return ResponseUtil.ok(codeList);
        }
        codeList = JacksonUtil.parseIntegerList(msg, "codeList");
        if (codeList != null && codeList.size() > 0 && codeList.size() < 4) {
            Map<String, String> map = new LinkedHashMap<>();
            for (int i = 0; i < codeList.size(); i++) {
                Integer code = codeList.get(i);
                switch (i) {
                    case 0:
                        //省
                        map.put("province", regionService.findNameByCode(code));
                        break;
                    case 1:
                        //市
                        map.put("city", regionService.findNameByCode(code));
                        break;
                    case 2:
                        //县
                        map.put("country", regionService.findNameByCode(code));
                        break;
                    default:
                        break;
                }
            }
            return ResponseUtil.ok(map);
        }
        return ResponseUtil.badArgument();
    }
}